package com.heny.demo.strategy;

import com.heny.demo.common.CommonErrorCode;
import com.heny.demo.common.CommonException;
import com.heny.demo.entity.TurnPointPOJO;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
 * @author litao.cc
 * @version XlsxProcessor.java v0.1 t2025/4/24 1:34
 * @date 2025/4/24 1:34
 * @description XlsxProcessor
 */
public class XlsxProcessor implements FileProcessorStrategy {
    private static final Logger logger = LoggerFactory.getLogger(XlsxProcessor.class);

    @Override
    public List<TurnPointPOJO> processFile(MultipartFile file) {
        List<TurnPointPOJO> result = new ArrayList<>();

        Workbook workbook = null;
        try {
            workbook = WorkbookFactory.create(file.getInputStream());
        } catch (IOException e) {
            logger.error("XlsxProcessor 文件处理失败：{0}", e.getMessage());
            throw new CommonException(CommonErrorCode.FILE_SYS_ERROR, e.getMessage());
        }
        Sheet sheet = workbook.getSheetAt(0);

        TurnPointPOJO row;
        for (int i = 0; i <= sheet.getLastRowNum(); i++) {
            Row currentRow = sheet.getRow(i);
            int rowNum = currentRow.getLastCellNum();
            if(rowNum == 4){
                row = new TurnPointPOJO();
                Cell c1 = currentRow.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                Cell c2 = currentRow.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                Cell c3 = currentRow.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                Cell c4 = currentRow.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                row.setIndex(c1.getStringCellValue());
                row.setX(c2.getNumericCellValue());
                row.setY(c3.getNumericCellValue());
                row.setZ(c4.getNumericCellValue());
                result.add(row);
            }
        }

        return result;
    }
}